function sData = serialData(s)
% Deze functie haalt data op van de seriele poort
DLE = 16;
STX = 17;
ETX = 18;
DLEMode = false;
DataMode = false;
min = 10;  %in cm
max = 200; %in cm

while(1)
    if(~DataMode)
        if(~DLEMode)
            if(exist('message','var'))
                message(2,:) = message(1,:);
            end
            [serialData, count, msg] = fread(s, 1, 'uchar');
            %serialData = fread(s,1,'uchar');
            if(isequal(size(serialData),[1 1]))
                message(1,:) = char2bin(serialData);
            else
                sData = [];
                return;
            end
    
            if(exist('message','var') && size(message,1)==2)
                if(hammingDecode([message(2,:); message(1,:)])==DLE)
                    DLEMode = true;
                end
            end
        else
            [serialData, count, msg] = fread(s, 2, 'uchar');
            %serialData = fread(s,2,'uchar');
            if(isequal(size(serialData),[2 1]))
                message = [char2bin(serialData(1));char2bin(serialData(2))];
                if(hammingDecode(message)==STX)
                    DataMode = true;
                    DLEMode = false;
                elseif(hammingDecode(message)==DLE)
                    DLEMode = true;
                else
                    DLEMode = false;
                end
            end 
        end
    else
        [serialData, count, msg] = fread(s, 2, 'uchar');
        %serialData = fread(s,2,'uchar');
        message = [char2bin(serialData(1));char2bin(serialData(2))];
        value = hammingDecode(message);
        if((value>0&&value<min) || (value>max&&value<255))
            value = 255;
        end
        if(~DLEMode)
            if(value==DLE)
                DLEMode = true;
            else
                if(exist('sData','var'))
                    sData = [sData, value];
                else
                    sData = value;
                end
            end
        else
            if(value==DLE)
                if(exist('sData','var'))
                    sData = [sData, value];
                else
                    sData = value;
                end
                DLEMode = false;
            elseif(value==ETX)
                return;
            else
                sData = [];
                return;
            end
        end
    end
end

end

